#pragma once
#include <functional>
#include <string>
#include <signal.h>

#include "Log.hpp"
#include "Socket.hpp"

using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : port_(port), callback_(callback)
    {
    }

    bool InitServer()
    {
        listen_sockfd_.Socket();
        listen_sockfd_.Bind(port_);
        listen_sockfd_.Listen();
        lg(Info, "init server .... done");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listen_sockfd_.Accept(&clientip, &clientport); // 传过去后，连接服务器的人的ip与port就能被带出来
            if (sockfd < 0)
                continue;
            lg(Info, "accept a new link,sockfd: %d,clientip: %s,clientport: %d", sockfd, clientip.c_str(), clientport);

            // 提供服务，采用多进程版
            // child
            if (fork() == 0)
            {
                // 子进程关掉不用的监听套接字
                listen_sockfd_.Close();
                std::string inbuffer_stream;
                // 数据计算
                while (true)
                {
                    char buffer[1280];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;

                        lg(Debug, "debug: \n%s", inbuffer_stream.c_str());
                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream);

                            // 如果报文不完整，回调后返回一个空串，然后if为真执行continue继续读
                            if (info.empty())
                                break;
                            lg(Debug, "debug, response:\n%s", info.c_str());
                            lg(Debug, "debug:\n%s", inbuffer_stream.c_str());

                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else if (n == 0)
                        break;
                    else
                        break;
                }

                exit(0); // 子进程可以直接退，因为SIGCHLD已经被忽略
            }

            // 父进程关掉子不用的通信套接字
            close(sockfd);
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t port_;
    Sock listen_sockfd_;
    func_t callback_;
};